Looping

The basic concept of looping is very simple—a loop repeats the same block of code an arbitrary number of times. All loops contain three elements: an initialization, which first sets values; a condition to continue, which decides when the loop will stop; and an updating condition that specifies what will change each time the looped code is run.

If the condition to continue is always met, the loop will continue to run for the life of your program—this is called an infinite loop. An infinite loop is a bug, as your program cannot progress or respond if it is stuck in one.

There are several types of loops in C++ that are specifically suited for different situations. However, they all include this basic structure and can hence technically be used interchangeably.

As with other control flow code, if you only have one statement in a loop block, you can omit the curly brackets.

While Loops

The simplest type of loop is the while loop, which only explicitly contains the continue condition. The block of code will simply be run while a boolean expression evaluates to true. The syntax is also quite simple: type the keyword "while," followed by your boolean expression in parenthesis. When your program gets to the loop, it will test your condition, and if it is true, it will run the looped block. When it gets to the end of the block, it will test your condition again, and so on. Because the while loop only explicitly specifies one of the three pieces, you have to implement the other two parts of the loop yourself: before your loop you must perform the initialization, and within the loop you must implement your updating condition. While loops are usually used for event triggered loops, where the updating condition is invalidated when something specific happens in the code. For example, a while loop is well suited to count through a string, or display a menu system, whereas the for loop is more suitable for when you know exactly how many times you want the loop to run.

char selection;
bool continueProgram = true;

while(continueProgram) {
	cout << “Continue (y/n): “
	cin >> selection;
	if(selection == 'n')
		continueProgram = false;
}

Do While Loops

The do while loop is almost exactly the same as the while loop, except in a do while, the loop code will always be run at least once. Basically, your program will go through the loop once under any condition, then it will check your continue condition. If the condition evaluates to true, your program will go back to the start of the loop, and so on. The syntax is also very similar, except that you start with the keyword "do," and put the "while" statement at the end of the code block, followed by a semicolon. Do while loops are especially useful in applications such as menu systems, where you know the code should be run at least once.

do {
	// do things, this will always happen at least once
	// update your condition
} while(condition);

For Loops

The third type of loop is the for loop. The for loop does essentially the same things as a while loop, but in a more compact manner, and is more suited to when you know exactly how many times your block of code should be run. The syntax of a for loop has five parts: first, the keyword "for," followed by parenthesis. There are three statements you must include in these parenthesis. First, there is the initializing statement. This first statement will be run once when the program first gets to the loop, and never again. Generally, here you want to set up variables or counters that will be used in the loop. Then, add a semicolon to end the first statement and start the second one. The second statement describes the continue condition of the loop, and must be a Boolean expression. Finally, add another semicolon and the third statement, which is the updating condition. This statement will be run each time your program gets to the end of the loop. Know that the updating condition is always run before checking the continue condition. This third statement often includes some sort of numerical manipulation of a counter variable, such as adding one to it each time. Finally, you can add multiple operations to the first and third statements by simply adding a comma between each one.

for(int i = 0; i < 20; i++) {
	cout << “Loop is on number “ << i << endl;
}
for(pizza = 0, steve = 10; pizza <= steve; pizza++, steve--)
	cout << “Pizza is “ << steve – pizza << “ less than steve.” << endl;

You should always pay close attention to at what values you start and end your loop, as improper use of greater than/less than/or equal to can lead to what are called "off-by-one" errors, where your loop will run one too many or too few times. Be careful of these errors, as they can be hard to find and very annoying to waste time on.

The first example would loop between values i = 0 and i = 19. On the other hand, if the conditional statement had a "<=" to instead of just "<", it would loop between i = 0 and i = 20.

Nesting Loops

Just like you can nest conditional statements, you can nest loops. It works just as you’d think—the outer loop runs the smaller loop however many times, and each time the inner loop is run, it runs its block however many times. This technique will be especially useful when we get to topics such as multidimensional arrays. In this example, the numbers 0-1, 0-2, etc will display, then 1-1, 1-2, etc...

for(int i = 0; i < 10; i++) {
	for(int j = 0; j < 10; j++)	{
		cout << i << “-“ << j << “ “;   
	}
	cout << endl;
}

Recursion

Finally, there is the last type of looping—looping without loops. You’ve probably heard of it before, and it’s recursion. Recursion is defined as the process of a function calling itself. There are several forms of recursion, but what we’ll cover for now are tail-recursive functions. A tail-recursive function simply begins with a conditional to end recursion, and if that is not triggered, it will call itself with some sort of modified parameters.

int addFrom(int x) {
	if(x == 1)
		return 1;
	else
		return x + addFrom(x – 1);
}

This function will take a value, and if that value is equal to one, it will simply return 1. However, if the value is not one, it will return the value plus the return of itself, called with one less than x. This process will continue until the value of x – 1 is equal to 1, in which case the final call will return 1, and the return values will cascade back up, adding each returned value to the last. It will eventually end up with x + (x – 1) + (x – 2) + … + 1, or the number plus each integer lower than it until 1.

If this seems a bit hard to wrap your head around, try to think of it visually:

Programming Exercises

  1. Write a function that calculates a factorial using a loop, and one that calculates it using recursion.
  2. Write a function that calculates a value to an exponent. It should be able to handle any integer exponent (i.e. positive and negative). You can use a loop, recursion, or both for this.
  3. Write a function that checks if a number is prime.